package org.example.aop;

import cn.hutool.jwt.JWTUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.example.domain.Logs;
import org.example.domain.User;
import org.example.service.LogsService;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Aspect
@Component
public class UserAop {
    @Autowired
    HttpServletRequest request;
    @Autowired
    UserService userService;
    @Autowired
    LogsService logsService;
    @After(value = "@annotation(org.example.aop.Annno)&&@annotation(annno)")
    public void aop(JoinPoint joinPoint, Annno annno){
        System.out.println("记录aop日志"+annno.value());
        String token = request.getHeader("token");
        Logs logs = new Logs();
        if(token==null){
            logs.setUsername("新用户登录");
        }else{
            Integer uid = (Integer) JWTUtil.parseToken(token).getPayload("uid");
            User byId = userService.getById(uid);
            System.out.println(byId+"1111111111111111"+byId.getUsername());
            logs.setUsername(byId.getUsername()+"重新登录");
        }
        String ip = request.getRemoteAddr();
        String name = joinPoint.getSignature().getName();
        logs.setIp(ip);
        logs.setName(name);
        logs.setContext(annno.value());
        logs.setCreateTime(new Date());
        logs.setFlag(0);
        logsService.save(logs);
    }
}
